package com.jiuqi.bi.irp.inforesource.dao;

import com.jiuqi.bi.bsp.authority2.storage.dao.DAOUtil;
import com.jiuqi.bi.database.DBException;
import com.jiuqi.bi.database.DatabaseManager;
import com.jiuqi.bi.database.IDatabase;
import com.jiuqi.bi.database.paging.IPagingSQLBuilder;
import com.jiuqi.bi.irp.core.enums.BooleanEnum;
import com.jiuqi.bi.irp.core.enums.DataTypeEnum;
import com.jiuqi.bi.irp.core.item.DBDataStructure;
import com.jiuqi.bi.irp.core.util.DataTableJudgeUtil;
import com.jiuqi.bi.util.Html;
import com.jiuqi.bi.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Date;
import java.util.stream.Collectors;

@Repository
public class IResStructureDataManageDao {

    public void addData(Connection conn, String tableName, List<String> fieldNames,
                        Map<String, Object> fieldValueDictronary,
                        Map<String, DBDataStructure> fieldAttributeDictronary) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("INSERT INTO ");

        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        stringBuffer.append(Html.cleanNonIdentifier(tableName));

        stringBuffer.append("(");
        List<String> toInsertFieldNames = new ArrayList<>();
        Queue<String> paramQueue = new LinkedList<>();
        for (int i = 0; i <= fieldNames.size() - 1; i++) {
            String fieldName = fieldNames.get(i);
            Object fieldValue = fieldValueDictronary.get(fieldName);

            if (ObjectUtils.isEmpty(fieldValue)) continue;

            toInsertFieldNames.add(fieldName);
            paramQueue.add(fieldName);
        }
        stringBuffer.append(String.join(",", toInsertFieldNames));
        stringBuffer.append(")");
        stringBuffer.append(" VALUES (");
        for (int i = 1; i <= paramQueue.size(); i++) {
            stringBuffer.append("?");
            if (i != paramQueue.size())
                stringBuffer.append(",");
        }
        stringBuffer.append(")");
        String addSQL = stringBuffer.toString();

        try (PreparedStatement ps = conn.prepareStatement(addSQL)) {
            int paramIndex = 1;
            while (!paramQueue.isEmpty()) {
                String curFieldName = paramQueue.remove();
                Object paramValue = fieldValueDictronary.get(curFieldName);
                DBDataStructure fieldAttribute = fieldAttributeDictronary.get(curFieldName);
                setParamValueWithExactType(ps, paramIndex++, paramValue, fieldAttribute);
            }
            ps.execute();
        }
    }

    public void modifyDataByPK(Connection conn, String tableName, List<String> primaryKeyNameList,
                               List<String> commonFieldNameList,
                               Map<String, Object> fieldValueDictronary,
                               Map<String, DBDataStructure> fieldAttributeDictronary) throws Exception {
        Queue<String> sqlParamQueue = new LinkedList<>();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("UPDATE ");

        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        stringBuffer.append(Html.cleanNonIdentifier(tableName));

        stringBuffer.append(" SET ");
        for (int i = 0; i <= commonFieldNameList.size() - 1; i++) {
            String curCommonFieldName = commonFieldNameList.get(i);
            stringBuffer.append(curCommonFieldName + "=? ");
            if (i != commonFieldNameList.size() - 1)
                stringBuffer.append(",");
            sqlParamQueue.add(curCommonFieldName);
        }
        stringBuffer.append("WHERE ");
        for (int i = 0; i <= primaryKeyNameList.size() - 1; i++) {
            String curPrimaryKeyName = primaryKeyNameList.get(i);
            stringBuffer.append(curPrimaryKeyName + "=? ");
            if (i != primaryKeyNameList.size() - 1)
                stringBuffer.append(" AND ");
            sqlParamQueue.add(curPrimaryKeyName);
        }
        String modifySQL = stringBuffer.toString();

        try (PreparedStatement ps = conn.prepareStatement(modifySQL)) {
            int paramIndex = 1;
            while (!sqlParamQueue.isEmpty()) {
                String curFieldName = sqlParamQueue.remove();
                Object paramValue = fieldValueDictronary.get(curFieldName);
                DBDataStructure fieldAttribute = fieldAttributeDictronary.get(curFieldName);
                setParamValueWithExactType(ps,paramIndex++,paramValue,fieldAttribute);
            }
            ps.execute();
        }
    }

    public void modifyDataByAllFields(Connection conn, String tableName,
                                      List<String> oldFieldNameList,
                                      List<String> newFieldNameList,
                                      Map<String, Object> oldFieldValueDictronary,
                                      Map<String, Object> newFieldValueDictronary,
                                      Map<String, DBDataStructure> fieldAttributeDictronary) throws Exception {
        Queue<String> sqlNewParamQueue = new LinkedList<>();
        Queue<String> sqlOldParamQueue = new LinkedList<>();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("UPDATE ");

        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        stringBuffer.append(Html.cleanNonIdentifier(tableName));

        stringBuffer.append(" SET ");
        for (int i = 0; i <= newFieldNameList.size() - 1; i++) {
            String fieldName = newFieldNameList.get(i);
            stringBuffer.append(fieldName + "=? ");
            if (i != newFieldNameList.size() - 1)
                stringBuffer.append(",");
            sqlNewParamQueue.add(fieldName);
        }
        stringBuffer.append("WHERE ");
        List<String> conditions = new ArrayList<>();
        for (int i = 0; i <= oldFieldNameList.size() - 1; i++) {
            String fieldName = oldFieldNameList.get(i);
            Object oldFieldValue = oldFieldValueDictronary.get(fieldName);

            if (ObjectUtils.isEmpty(oldFieldValue)) continue;

            conditions.add(fieldName + "=?");
            sqlOldParamQueue.add(fieldName);
        }
        String unionCondition = String.join(" AND ", conditions);
        stringBuffer.append(unionCondition);
        String modifySQL = stringBuffer.toString();

        try (PreparedStatement ps = conn.prepareStatement(modifySQL)) {
            int paramIndex = 1;
            while (!sqlNewParamQueue.isEmpty()) {
                String curFieldName = sqlNewParamQueue.remove();
                Object paramValue = newFieldValueDictronary.get(curFieldName);
                DBDataStructure fieldAttribute = fieldAttributeDictronary.get(curFieldName);
                setParamValueWithExactType(ps,paramIndex++,paramValue,fieldAttribute);
            }
            while (!sqlOldParamQueue.isEmpty()) {
                String curFieldName = sqlOldParamQueue.remove();
                Object paramValue = oldFieldValueDictronary.get(curFieldName);
                DBDataStructure fieldAttribute = fieldAttributeDictronary.get(curFieldName);
                setParamValueWithExactType(ps,paramIndex++,paramValue,fieldAttribute);
            }
            ps.execute();
        }
    }

    public void deleteDataByPK(Connection conn, String tableName, List<String> tablePKNameList,
                               List<List<Object>> deleteParamList,
                               Map<String, DBDataStructure> fieldAttributeDictronary) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("DELETE FROM ");

        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        stringBuffer.append(Html.cleanNonIdentifier(tableName));

        stringBuffer.append(" WHERE ");
        for (int i = 0; i <= tablePKNameList.size() - 1; i++) {
            String pkName = tablePKNameList.get(i);
            stringBuffer.append(pkName + "=? ");
            if (i != tablePKNameList.size() - 1)
                stringBuffer.append(" AND ");
        }

        String deleteSQL = stringBuffer.toString();
        try (PreparedStatement ps = conn.prepareStatement(deleteSQL)) {
            for (List<Object> deleteParam : deleteParamList) {
                for (int i = 1; i <= deleteParam.size(); i++) {
                    Object paramValue = deleteParam.get(i - 1);
                    String curFieldName = tablePKNameList.get(i - 1);
                    DBDataStructure fieldAttribute = fieldAttributeDictronary.get(curFieldName);
                    setParamValueWithExactType(ps,i,paramValue,fieldAttribute);
                }
                ps.addBatch();
            }
            ps.executeBatch();
        }
    }

    public void deleteDataByAllFields(Connection conn, String tableName, List<Map<String, Object>> dataBaseExistRows,
                                      Map<String, DBDataStructure> fieldAttributeDictronary) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();

        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        tableName = Html.cleanNonIdentifier(tableName);

        for (Map<String, Object> curRowFieldsInfo : dataBaseExistRows) {
            stringBuffer.delete(0, stringBuffer.length());

            stringBuffer.append("DELETE FROM ");
            stringBuffer.append(tableName);
            stringBuffer.append(" WHERE ");
            List<String> conditions = new ArrayList<>();
            int num = curRowFieldsInfo.keySet().size();
            List<String> usedFieldNames = new ArrayList<>(num);


            List<String> allFieldNames = new ArrayList<>(curRowFieldsInfo.keySet());
            for (int i = 0; i <= allFieldNames.size() - 1; i++) {
                String curFieldName = allFieldNames.get(i);
                Object curFieldValue = curRowFieldsInfo.get(curFieldName);

                if (ObjectUtils.isEmpty(curFieldValue)) continue;

                conditions.add(curFieldName + "=?");
                usedFieldNames.add(curFieldName);
            }
            String unionCondition = String.join(" AND ", conditions);
            stringBuffer.append(unionCondition);
            String deleteSQL = stringBuffer.toString();
            try (PreparedStatement ps = conn.prepareStatement(deleteSQL)) {
                for (int i = 1; i <= usedFieldNames.size(); i++) {
                    String curFieldName = usedFieldNames.get(i - 1);
                    Object paramValue = curRowFieldsInfo.get(curFieldName);
                    DBDataStructure fieldAttribute = fieldAttributeDictronary.get(curFieldName);
                    setParamValueWithExactType(ps,i,paramValue,fieldAttribute);
                }
                ps.execute();
            }

        }
    }

    public JSONArray queryByFilterAndPage(Connection conn, String pageSize, String currentPage, String tableName,
                                          List<String> fieldNames,
                                          Map<String, Object> fieldValueDictronary,
                                          List<DBDataStructure> structures) throws Exception {
        JSONArray result = new JSONArray();
        Queue<String> paramQueue = new LinkedList<>();

        String filterSql = buildFilterSql(conn, tableName, fieldNames, fieldValueDictronary, paramQueue,true);
        String filterAndPageSql = buildPageSql(conn, pageSize, currentPage, filterSql);

        try (PreparedStatement ps = conn.prepareStatement(filterAndPageSql)) {
            int paramIndex = 1;
            while (!paramQueue.isEmpty()) {
                Object paramValue = fieldValueDictronary.get(paramQueue.remove());
                ps.setObject(paramIndex++, "%" + paramValue + "%");
            }
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    result.put(readElement(rs, structures));
                }
            }
        }
        return result;
    }

    public JSONArray queryByFilter(Connection conn, String tableName, List<String> fieldNames,
                                   Map<String, Object> fieldValueDictronary,
                                   List<DBDataStructure> structures) throws Exception {
        JSONArray result = new JSONArray();
        Queue<String> paramQueue = new LinkedList<>();

        String filterSql = buildFilterSql(conn, tableName, fieldNames, fieldValueDictronary, paramQueue,true);

        try (PreparedStatement ps = conn.prepareStatement(filterSql)) {
            int paramIndex = 1;
            while (!paramQueue.isEmpty()) {
                Object paramValue = fieldValueDictronary.get(paramQueue.remove());
                ps.setObject(paramIndex++, "%" + paramValue + "%");
            }
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    result.put(readElement(rs, structures));
                }
            }
        }
        return result;
    }

    public int fuzzyQueryTotalSize(Connection conn, String tableName, List<String> fieldNames,
                                   Map<String, Object> fieldValueDictronary) throws Exception {
        int rowCount = 0;
        Queue<String> paramQueue = new LinkedList<>();

        String filterSql = buildFilterQueryRowCountSql(conn, tableName, fieldNames, fieldValueDictronary, paramQueue);

        try (PreparedStatement ps = conn.prepareStatement(filterSql)) {
            int paramIndex = 1;
            while (!paramQueue.isEmpty()) {
                Object paramValue = fieldValueDictronary.get(paramQueue.remove());
                ps.setObject(paramIndex++, "%" + paramValue + "%");
            }
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    rowCount = rs.getInt(1);
                }
            }
        }
        return rowCount;
    }

    private String buildFilterSql(Connection conn, String tableName, List<String> fieldNames,
                                  Map<String, Object> fieldValueDictronary,
                                  Queue<String> paramQueue,Boolean isFuzzy) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT * FROM ");

        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        stringBuffer.append(Html.cleanNonIdentifier(tableName));


        List<String> toQueryFieldNames = new ArrayList<>();
        for (int i = 0; i <= fieldNames.size() - 1; i++) {
            String fieldName = fieldNames.get(i);
            Object fieldValue = fieldValueDictronary.get(fieldName);

            if (ObjectUtils.isEmpty(fieldValue)) continue;

            if (isFuzzy)
                toQueryFieldNames.add(fieldName + " like ?");
            else
                toQueryFieldNames.add(fieldName + " = ?");

            paramQueue.add(fieldName);
        }

        if (!paramQueue.isEmpty())
            stringBuffer.append(" WHERE ")
                    .append(String.join(" and ", toQueryFieldNames));
        return stringBuffer.toString();
    }

    private String buildFilterQueryRowCountSql(Connection conn, String tableName, List<String> fieldNames,
                                  Map<String, Object> fieldValueDictronary,
                                  Queue<String> paramQueue) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT COUNT(1) FROM ");

        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        stringBuffer.append(Html.cleanNonIdentifier(tableName));


        List<String> toQueryFieldNames = new ArrayList<>();
        for (int i = 0; i <= fieldNames.size() - 1; i++) {
            String fieldName = fieldNames.get(i);
            Object fieldValue = fieldValueDictronary.get(fieldName);

            if (ObjectUtils.isEmpty(fieldValue)) continue;

            toQueryFieldNames.add(fieldName + " like ?");

            paramQueue.add(fieldName);
        }

        if (!paramQueue.isEmpty())
            stringBuffer.append(" WHERE ")
                    .append(String.join(" and ", toQueryFieldNames));
        return stringBuffer.toString();
    }

    private String buildPageSql(Connection conn, String pageSize, String pageIndex, String baseSql) throws SQLException, DBException {
        BigInteger pageSizeBig = new BigInteger(pageSize);
        BigInteger pageIndexBig = new BigInteger(pageIndex);
        BigInteger big1 = new BigInteger("1");
        BigInteger rownumPage = pageSizeBig.multiply(pageIndexBig);
        BigInteger rnPage = pageSizeBig.multiply(pageIndexBig.subtract(big1));

        IDatabase database = DatabaseManager.getInstance().findDatabaseByConnection(conn);
        IPagingSQLBuilder pagingSQLBuilder = database.createPagingSQLBuilder();
        pagingSQLBuilder.setRawSQL(baseSql);

        int rnPageInt = rnPage.intValue();
        int rownumPageInt = rownumPage.intValue();

        return pagingSQLBuilder.buildSQL(rnPageInt, rownumPageInt);
    }

    private static JSONObject readElement(ResultSet rs, List<DBDataStructure> structures) {

        JSONObject reuslt = new JSONObject();
        for (int j = 0; j < structures.size(); j++) {
            DBDataStructure struct = structures.get(j);
            String value = "";
            try {
                int dataType = struct.getDataType();
                if (dataType != DataTypeEnum.BLOB.id()) {
                    value = rs.getString(struct.getFieldName());
                }

                if (dataType == DataTypeEnum.DATE.id()) {
                    if (StringUtils.isNotEmpty(value)) {
                        value = value.length() > 10 ? value.substring(0, 10) : value;
                        LocalDate dateTime = LocalDate.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        value = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    }
                } else if (dataType == DataTypeEnum.BLOB.id()) {
                    byte[] bytes = rs.getBytes(struct.getFieldName());
                    if (bytes.length > 0) {
                        value = new String(bytes, "UTF-8");
                    }
                }
            } catch (Exception e) {
                value = "";
            }
            reuslt.put(struct.getFieldName(), value);
        }

        return reuslt;
    }


    /***
     * 数据管理-清理数据
     * @param tableName
     * @throws Exception
     */
    public void clearAllDataByGuid(Connection conn, String tableName) throws Exception {
        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        try (PreparedStatement st = conn.prepareStatement("DELETE FROM  " + Html.cleanNonIdentifier(tableName))) {
            st.executeUpdate();
        }
    }


    /**
     * @param conn
     * @param tableName
     * @param entities
     * @param itemList
     * @throws Exception
     */
    public void saveImportFile(Connection conn, String tableName, List<DBDataStructure> entities, JSONArray itemList) throws Exception {

        List<String> columns = entities.stream()
                .map(item -> DataTableJudgeUtil.judgeDatabaseKeyword(conn, item.getFieldName()))
                .collect(Collectors.toList());

        String[] arrayAdd = columns.toArray(new String[columns.size()]);

        //创建执行SQL
        boolean iskeyword = DataTableJudgeUtil.judgeDatabaseKeywords(conn, tableName);
        //表关键字处理
        if (iskeyword) {
            tableName = "\"" + tableName + "\"";
        }
        String addSql = DAOUtil.createSQL_Insert(tableName, arrayAdd);
        try (PreparedStatement ps = conn.prepareStatement(addSql)) {

            for (int i = 0; i < itemList.length(); i++) {
                JSONObject item = itemList.getJSONObject(i);
                //设置值
                setEleObject(ps, item, entities);
                ps.addBatch();
            }

            ps.executeBatch();
        }
    }

    private void setEleObject(PreparedStatement st, JSONObject json, List<DBDataStructure> entities) throws Exception {
        int index = 1;
        for (int i = 0; i < entities.size(); i++) {
            DBDataStructure structure = entities.get(i);
            String name = structure.getFieldName();
            int dataType = structure.getDataType();

            if (dataType == DataTypeEnum.BOOLEAN.id()) {
                st.setBoolean(i + 1, json.optBoolean(name));
            } else if (dataType == DataTypeEnum.INTEGER.id()) {
                int value = json.optInt(name);
                String strValue = json.optString(name);
                if (strValue.equals("false")) {
                    value = BooleanEnum.NO.id();
                } else if (strValue.equals("true")) {
                    value = BooleanEnum.YES.id();
                }
                //空导入显示空，不显示0
                if (StringUtils.isNotEmpty(strValue)) {
                    st.setInt(i + 1, value);
                } else {
                    st.setString(i + 1, null);
                }

            } else if (dataType == DataTypeEnum.LONG.id()) {
                st.setLong(i + 1, json.optLong(name));
            } else if (dataType == DataTypeEnum.FLOAT.id()) {
                //空导入显示空，不显示0
                String strValue = json.optString(name);
                if (StringUtils.isNotEmpty(strValue)) {
                    Double optDouble = Double.valueOf(json.optDouble(name));
                    optDouble = optDouble.isNaN() ? Double.valueOf(0) : optDouble;
                    st.setDouble(i + 1, optDouble.doubleValue());
                } else {
                    st.setString(i + 1, null);
                }

            } else if (dataType == DataTypeEnum.DATE.id()) {
                String strValue = json.optString(name);
                if (StringUtils.isNotEmpty(strValue)) {
                    Timestamp timestamp = Timestamp.valueOf(json.optString(name) + " 00:00:00.000000");
                    st.setTimestamp(i + 1, timestamp);
                } else {
                    st.setString(i + 1, null);
                }

            } else if (dataType == DataTypeEnum.BLOB.id()) {
                String blobValue = json.optString(name);
                if (StringUtils.isNotEmpty(blobValue)) {
                    byte[] bytes = blobValue.getBytes(StandardCharsets.UTF_8);
                    st.setBytes(i + 1, bytes);
                } else {
                    st.setString(i + 1, null);
                }

            } else {
                st.setString(i + 1, json.optString(name));
            }
        }
    }

    public JSONArray normalQuery(Connection conn, String tableName, List<String> fieldNames,
                              Map<String, Object> fieldValueDictronary,
                              Map<String, DBDataStructure> fieldAttributeDictronary) throws Exception {
        JSONArray result = new JSONArray();
        Queue<String> paramQueue = new LinkedList<>();

        String filterSql = buildFilterSql(conn, tableName, fieldNames, fieldValueDictronary, paramQueue,false);

        try (PreparedStatement ps = conn.prepareStatement(filterSql)) {
            int paramIndex = 1;
            while (!paramQueue.isEmpty()) {
                String curFieldName = paramQueue.remove();
                Object paramValue = fieldValueDictronary.get(curFieldName);
                DBDataStructure fieldAttribute = fieldAttributeDictronary.get(curFieldName);
                setParamValueWithExactType(ps,paramIndex++,paramValue,fieldAttribute);
            }

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    result.put(readElement(rs, new ArrayList<>(fieldAttributeDictronary.values())));
                }
            }
        }
        return result;
    }

    private void setParamValueWithExactType(PreparedStatement ps, int paramIndex, Object paramValue, DBDataStructure fieldAttribute) throws SQLException, ParseException {
        int dataType = fieldAttribute.getDataType();
        if (dataType == DataTypeEnum.BOOLEAN.id()) {
            String tempParamValue = (String) paramValue;
            if (StringUtils.isNotEmpty(tempParamValue))
                ps.setBoolean(paramIndex, Boolean.parseBoolean((String) paramValue));
            else
                ps.setObject(paramIndex, null);
        } else if (dataType == DataTypeEnum.INTEGER.id()) {
            String tempParamValue = (String) paramValue;
            if (StringUtils.isNotEmpty(tempParamValue))
                ps.setInt(paramIndex, Integer.parseInt((String) paramValue));
            else
                ps.setObject(paramIndex, null);
        } else if (dataType == DataTypeEnum.LONG.id()) {
            String tempParamValue = (String) paramValue;
            if (StringUtils.isNotEmpty(tempParamValue))
                ps.setLong(paramIndex, Long.parseLong((String) paramValue));
            else
                ps.setObject(paramIndex, null);
        } else if (dataType == DataTypeEnum.FLOAT.id()) {
            String tempParamValue = (String) paramValue;
            if (StringUtils.isNotEmpty(tempParamValue))
                ps.setDouble(paramIndex, Double.parseDouble((String) paramValue));
            else
                ps.setObject(paramIndex, null);
        } else if (dataType == DataTypeEnum.DATE.id()) {
            if (!ObjectUtils.isEmpty(paramValue)) {
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sf.parse(paramValue.toString());
                Timestamp timestamp = new Timestamp(date.getTime());
                ps.setTimestamp(paramIndex, timestamp);
            } else {
                ps.setObject(paramIndex, null);
            }
        } else if (dataType == DataTypeEnum.BLOB.id()) {
            String blobValue = paramValue.toString();
            if (StringUtils.isNotEmpty(blobValue)) {
                byte[] bytes = blobValue.getBytes(StandardCharsets.UTF_8);
                ps.setBytes(paramIndex, bytes);
            } else {
                ps.setObject(paramIndex, null);
            }
        } else {
            ps.setString(paramIndex, paramValue.toString());
        }
    }
}
